package com.example.filter;

import com.alibaba.fastjson.JSON;
import com.example.entity.Result;
import com.example.utils.WarehouseConstants;
import io.netty.util.internal.StringUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:tjf
 * @Description: 自定义用于过滤未登录用户的过滤器
 */
public class SecurityFilter implements Filter {
    private StringRedisTemplate stringRedisTemplate;

    public void setRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // 白名单
        List<String> urlList = new ArrayList<>();
        urlList.add("/captcha/captchaImage");
        urlList.add("/login");
        urlList.add("/product/img-upload");

        // 获取访问的资源路径  若访问的是/static/img/upload目录下的图片则直接放行
        String path = request.getServletPath();
        if (urlList.contains(path) || path.contains("/img/upload")){ // 是白名单
            chain.doFilter(request, response);// 放行
            return;
        }

        // 令牌检查
        String token = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
        if (StringUtils.hasText(token) && stringRedisTemplate.hasKey(token)){
            chain.doFilter(request, response);
            return;
        }

        // 未登录，不能访问资源
        Result result = Result.err(Result.CODE_ERR_UNLOGINED, "您未登录！");
        // 转为json字符串
        String jsonStr = JSON.toJSONString(result);
        // 设置响应头信息
        response.setContentType("text/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(jsonStr);
        out.flush();
        out.close();
    }
}
